#include "thread.hpp"
// #include <iostream>
//  #include <pthread.h>
// int tickets = 1000;//将票数设为1000
// //初始化
// pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
// void ticket()
// {
//     while (true)
//     {
//         //加锁
//         pthread_mutex_lock(&gmutex);
//         if (tickets > 0)
//         {
//             usleep(10000);
//             //买票
//             std::cout << "tickets还有:" << tickets << std::endl;
//             tickets--;
//             //数据入库
//             //usleep(10000);
//             //解锁
//             pthread_mutex_unlock(&gmutex);
//         }
//         else
//         {
//             pthread_mutex_unlock(&gmutex);
//             break;
//         }
//     }
// }
// struct ThredData
// {
//     pthread_mutex_t _mutex;
// }
//初始化
//pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
int tickets = 1000;//将票数设为1000
void ticket(pthread_mutex_t& _mutex)
{
    while (true)
    {
        //加锁
        pthread_mutex_lock(&_mutex);
        if (tickets > 0)
        {
            usleep(10000);
            //买票
            std::cout << "tickets还有:" << tickets << std::endl;
            tickets--;
            //数据入库
            //usleep(10000);
            //解锁
            pthread_mutex_unlock(&_mutex);
        }
        else
        {
            pthread_mutex_unlock(&_mutex);
            break;
        }
    }
}
int main()
{
    std::vector<ThreadModule::Thread<pthread_mutex_t>> threads;
    pthread_mutex_t _mutex;
    //初始化
    pthread_mutex_init(&_mutex,nullptr);
    for (int i = 0; i < 4; i++)
    {
        ThreadModule::Thread<pthread_mutex_t> t(ticket,_mutex);
        threads.push_back(t);
    }

    for (auto &thread : threads)
    {
        thread.Start();
    }
    for (auto &thread : threads)
    {
        thread.Join();
    }
    //销毁
    pthread_mutex_destroy(&_mutex);
    return 0;
}